//app.js
var api = require("./mars/services/api.js");
let that;
App({
  onLaunch: function() {
    that = this;
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs);
    this.deviceInfo = this.promise.getDeviceInfo();
    wx.getSystemInfo({
      success: res => {
        let modelmes = res.model;
        if (modelmes.search('iPhone X') != -1) {
          that.globalData.isIphoneX = true
        }
      }
    });
  },
  getUserInfo: function(cb) {
    var that = this;
    // if(wx.getStorageSync('user').id) return;
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success(res) {
              console.log(res.userInfo)
              let userInfo = res.userInfo;
              wx.login({
                success: function (res) {
                  if (res.code) {
                    //发起网络请求
                    console.log(res.code);
                    api.WxRequest(api.checkIsNew, {
                      code: res.code,
                      userInfo: userInfo
                    }, (res) => {
                      wx.setStorageSync('user', res.data);
                    });
                  }
                }
              });
            }
          });
        } else {
          setTimeout(function() {
            wx.navigateTo({
              url: '/pages/login/login',
            });
          }, 0);
        }
      }
    })

    // let user = wx.getStorageSync('user');
    // if (user.user_id) {
    //   return user;
    // } else {
    //   console.log('从app.js进入')
    // }
  },
  promise: {
    getDeviceInfo: function() { //获取设备信息
      let promise = new Promise((resolve, reject) => {
        wx.getSystemInfo({
          success: function(res) {
            resolve(res)
          },
          fail: function() {
            reject()
          }
        })
      })
      return promise
    }
  },
  globalData: {
    userInfo: {
      user_id: 123456,
    },
    isIphoneX: false,
  },
  goIndex: function() {
    wx.navigateTo({
      url: '/pages/index/index'
    })
  },
  format: function(_from, target) {
    for (var key in target) {
      if (key != "__webviewId__" && _from[key]) {
        target[key] = _from[key];
      }
    }
    return target;
  },
  getGid: (function() { //全局唯一id
    let id = 0
    return function() {
      id++
      return id
    }
  })()
})